/*
 * @author zzr
 * @date: 2025/05/10  16:17
 * @description: 自己实现一个简单的线程池~
 * 注意：此处不考虑线程数量的增加和减少，只在构造方法中确定线程的数量~
 */

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoll {

    // List 结构存储线程
    private List<Thread> list = new ArrayList<>();
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    private volatile boolean isShutDown = false;
    public MyThreadPoll (int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                    while (!isShutDown ) {
                        try {
                            Runnable runnable = queue.take();
                            runnable.run();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            break;
                        }
                    }
            });
            t.start();
            list.add(t);
        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        if (isShutDown) {
            System.out.println("线程池已经关闭，无法再添加");
        }
        queue.put(runnable);
    }
    public void shutDown () {
        for (Thread t : list) {
            t.interrupt();
        }
    }
}
public class Demo12 {

    public static void main(String[] args) throws InterruptedException {
        MyThreadPoll myThreadPoll = new MyThreadPoll(4);
        int n = 1000;
        for (int i = 0; i < n; i++) {
            int t = i;
            myThreadPoll.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("当前执行到" + t + "个线程" + Thread.currentThread().getName());
                }
            });
        }
        Thread.sleep(5000);
        myThreadPoll.shutDown();
        myThreadPoll.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("不能执行~");
            }
        });
    }
}
